/**
 * 
 */
package com.cqan.controller;

import static com.cqan.common.ViewName.CENTER;
import static com.cqan.common.ViewName.DOWN;
import static com.cqan.common.ViewName.HELP;
import static com.cqan.common.ViewName.LEFT;
import static com.cqan.common.ViewName.MAIN;
import static com.cqan.common.ViewName.RIGHT;
import static com.cqan.common.ViewName.TOP;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.cqan.account.entity.Authority;
import com.cqan.account.entity.User;
import com.cqan.account.entity.Authority.AuthType;
import com.cqan.account.service.AuthorityService;
import com.cqan.exception.AppException;
import com.cqan.util.CodeUtils;
import com.google.common.collect.Lists;

/**
 * @Description 后台系统视图映射
 * @author slaton.wu@gmail.com
 * @date 2012-7-6上午11:23:05
 * 
 */
@Controller
@RequestMapping("/admin")
@SuppressWarnings("rawtypes")
public class MainController extends BaseController {

	private static final Logger logger = Logger.getLogger("ds.debug");

	@Resource(name = "authorityService")
	private AuthorityService authorityService;

	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView main() {
		return new ModelAndView(MAIN);
	}

	@RequestMapping(value = "/top.htm", method = RequestMethod.GET)
	public ModelAndView top() {

		return new ModelAndView(TOP);
	}

	@RequestMapping(value = "/center.htm", method = RequestMethod.GET)
	public ModelAndView center() {

		return new ModelAndView(CENTER);
	}

	@RequestMapping(value = "/left.htm", method = RequestMethod.GET)
	public ModelAndView left() {
		ModelAndView mav = new ModelAndView(LEFT);
		User user = getUserDetails();
		if (user!=null) {
			List<GrantedAuthority> auths = user.getAuthorities();
			List<Long> aids = Lists.newArrayList();
			if (auths!=null&&auths.size()>0) {
				for (GrantedAuthority ga : auths) {
					Long aid = Long.parseLong(ga.getAuthority());
					if (!aids.contains(aid)) {
						aids.add(aid);
					}
				}
				List<Authority> menus = authorityService.get(aids);
				mav.addObject("menus", checkAuths(menus));
			}
			
		}
		return mav;
	}
	
	public List<Authority> checkAuths(List<Authority> menus){
		if (menus==null) {
			return null;
		}
		Iterator<Authority> it = menus.iterator();
		while (it.hasNext()) {
			Authority auth = (Authority) it.next();
			if (!auth.getAuthType().equals(AuthType.MENU)) {
				it.remove();
			}
		}
		return menus;
	}

	@RequestMapping(value = "/down.htm", method = RequestMethod.GET)
	public ModelAndView down() {

		return new ModelAndView(DOWN);
	}

	@RequestMapping(value = "/right.htm", method = RequestMethod.GET)
	public ModelAndView right() {

		return new ModelAndView(RIGHT);
	}
	@RequestMapping(value = "/help.htm", method = RequestMethod.GET)
	public ModelAndView help() {
		
		return new ModelAndView(HELP);
	}

	/**
	 * 生成验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws AppException
	 */
	@RequestMapping(value = "/code.htm", method = RequestMethod.GET)
	public ModelAndView code(HttpServletRequest request,
			HttpServletResponse response) throws AppException {
		int width = 55;
		int height = 23;
		try {
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = image.getGraphics();
			g.setColor(Color.WHITE);
			g.fillRect(0, 0, width, height);
			g.setFont(new Font("Arial", Font.PLAIN, 18));
			String code = RandomStringUtils.random(4, true, true);
			for (int i = 0; i < code.length(); i++) {
				g.setColor(CodeUtils.getRandomColor());
				g.drawString(String.valueOf(code.charAt(i)),
						(int) ((width * 0.23) * (i + 0.2)),
						(int) (height * 0.8));
			}
			request.getSession().setAttribute("validateCode", code);
			logger.debug("validateCode is " + code);
			g.dispose();
			ServletOutputStream output = response.getOutputStream();
			ImageOutputStream imageOut = ImageIO
					.createImageOutputStream(output);
			ImageIO.write(image, "JPEG", imageOut);
			imageOut.flush();
			imageOut.close();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new AppException("account.validateCode");
		}
		return null;
	}

}
